import { toast, getStorage, setStorage } from "../../utils/storage"
Page({
  data: {
    oldPwdIcon: 'closed-eye',
    newPwdIcon: 'closed-eye',
    cfmPwdIcon: 'closed-eye',
    oldPwdType: 'password',
    newPwdType: 'password',
    cfmPwdType: 'password',
    oldPassword: '',
    newPassword: '',
    cfmPassword: '',
    showNavigateBack: true
  },
  onLoad() {
    const user = getStorage("user");
    this.setData({ showNavigateBack: !user.firstLogin });
  },
  goback() {
    wx.navigateBack();
  },
  changePwdMode({ target: { id } }) {
    if (id === "old") {
      let icon = this.data.oldPwdIcon === "closed-eye" ? "eye-o" : "closed-eye";
      let type = this.data.oldPwdIcon === "closed-eye" ? "text" : "password";
      this.setData({ oldPwdIcon: icon, oldPwdType: type })
    }
    else if (id === "new") {
      let icon = this.data.newPwdIcon === "closed-eye" ? "eye-o" : "closed-eye";
      let type = this.data.newPwdIcon === "closed-eye" ? "text" : "password";
      this.setData({ newPwdIcon: icon, newPwdType: type })
    }
    else if (id === "cfm") {
      let icon = this.data.cfmPwdIcon === "closed-eye" ? "eye-o" : "closed-eye";
      let type = this.data.cfmPwdIcon === "closed-eye" ? "text" : "password";
      this.setData({ cfmPwdIcon: icon, cfmPwdType: type })
    }
  },
  async submit() {
    let { oldPassword, newPassword, cfmPassword } = this.data;
    oldPassword = oldPassword.trim();
    if (oldPassword.length < 6 || oldPassword.length > 16) {
      toast({ title: "请输入6-16位原始密码" });
      return;
    }
    newPassword = newPassword.trim();
    if (newPassword.length < 8 || newPassword.length > 16) {
      toast({ title: "请输入8-16位新密码" });
      return;
    }
    else if (newPassword === oldPassword) {
      toast({ title: '新密码不能与原始密码相同' });
      return;
    }
    else if (!/^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\W_!@#$%^&*`~()-+=]+$)(?![0-9\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\W_!@#$%^&*`~()-+=]{8,16}$/.test(newPassword)) {
      toast({ title: "新密码必须包含大写字母、小写字母、数字和特殊符号中的三种" });
      return;
    }

    cfmPassword = cfmPassword.trim();
    if (cfmPassword === "") {
      toast({ title: "请输入确认密码" });
      return;
    }
    else if (cfmPassword != newPassword) {
      toast({ title: "两次输入密码不一致" });
      return;
    }

    let { statusCode, data: { code, message } = {} } = await wx.$http.post("/quality/mgr/password", {
      "oldPassword": oldPassword,
      "newPassword": newPassword,
      "againPassword": cfmPassword
    }).catch();
    if (statusCode === 200 && code === 200) {
      let user = getStorage("user");
      if (user.firstLogin) {
        user.firstLogin = false;
        setStorage(wx.$USER_NAME, user);
        wx.redirectTo({
          url: '/pages/squra/squra',
        })
      }
    }
    else
      toast({ title: message });
  }
})